import pickle, base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录后合并cookie购物车数据到Redis
    :param request: 本次请求对象，获取cookie中的数据
    :param response: 本次响应对象，清除cookie中的数据
    :param user: 登录用户信息，获取user_id
    :return: response
    """
    # 获取cookies中的购物车数据
    cookie_cart_str = request.COOKIES.get('carts')
    # 如果不存在, 不需要合并
    if not cookie_cart_str:
        return response
    # 如果存在, 需要合并
    cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart_str.encode()))
    # 重点: 准备新的数据容器->保存新的sku_id:count, selected, unselected
    new_cart_dict = {}
    new_selected_add = []
    new_selected_remove = []

    # 遍历出cookies中的购物车数据
    for sku_id, cookie_dict in cookie_cart_dict.items():
        # 错误的数据结构
        # new_cart_dict[sku_id] = {
        #     'count': cookie_dict['count']
        # }
        new_cart_dict[sku_id] = cookie_dict['count']

        if cookie_dict['selected']:
            new_selected_add.append(sku_id)
        else:
            new_selected_remove.append(sku_id)
    # 根据新的数据结构, 合并到redis
    redis_con = get_redis_connection('carts')
    p1 = redis_con.pipeline()

    # 用cookie中的购物车商品数据部分覆盖redis中的购物车数据
    p1.hmset('carts_%s'%user.id, new_cart_dict)

    if new_selected_add:
        p1.sadd('selected_%s'%user.id, *new_cart_dict)
    else:
        p1.srem('selected_%s'%user.id, *new_selected_remove)
    p1.execute()

    response.delete_cookie('carts')

    return response